package org.ym.file.domain.model.rule.embed;

import lombok.*;
import org.ym.file.domain.model.rule.enums.RuleType;
import org.ym.file.domain.model.rule.enums.RuleTypeConverter;
import org.ym.tools.adapter.IgnoreField;

import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Embeddable;
import javax.persistence.Transient;
import java.io.Serializable;
import java.util.regex.Pattern;

/**
 * @author ym
 */
@Embeddable
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Builder
@EqualsAndHashCode
@ToString
public class RuleDetail implements Serializable {
    private static final long serialVersionUID = -6704408828007382377L;
    @Column(name = "rule",length = 200,nullable = false)
    private String rule;
    /**
     * 规则类型
     */
    @Column(name = "rule_type",length = 25,nullable = false)
    @Convert(converter = RuleTypeConverter.class)
    private RuleType ruleType;

    /**
     * 校验
     */
    @Transient
    @IgnoreField
    private Pattern pattern;
    /**
     * 当前文件是否符合要求
     * @param fileName 文件名称
     * @return true：符合 / false：不符合
     */
    public boolean isMatch(String fileName){
        boolean isMatch = false;
        switch (ruleType){
            case REG_MATCH:
                if(pattern == null) {
                    synchronized (this) {
                        if(pattern == null) {
                            pattern = Pattern.compile(rule);
                        }
                    }
                }
                isMatch = pattern.matcher(fileName).matches();
                break;
            case CONTAINS:
                isMatch = fileName.contains(rule);
                break;
            default:break;
        }
        return isMatch;
    }
}
